import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  // 设置页面标题
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  // 判断用户是否已登录
  const hasToken = store.getters.token

  if (hasToken) {
    // 如果有token
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      // 如果已token，切到首页，否则重定向到首页
      next({ path: '/' })
      // next()
      NProgress.done()
    } else {
      // 如果有token，且不是登录页，则放行
      next()
    }
  } else {
    /* has no token*/
    // 如果不在白名单中，则重定向到登录页
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next('/login')
      NProgress.done()
    }
  }
})

// 后置路由守卫
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
